<?php
class Customer_model extends CI_Model {
	
	function Customer_model() {
		parent::__construct ();
	}
	
	function add($data) {
		$this->db->where ( 'username =', $data ['username'] );
		$this->db->or_where ( 'email =', $data ['email'] );
		$query = $this->db->get ( 'customers' );
		if ($query->num_rows () > 0) {
			return FALSE;
		} else {
			return $this->db->insert ( 'customers', $data );
		}
	}
		
	function update($id, $data) {
		$this->db->where ( 'id', $id );
		return $this->db->update ( 'customers', $data );
	}
	
	function delete($id) {
		$this->db->where ( 'id', $id );
		return  $this->db->delete ( 'customers' );
	}
	
	function searchByProvince($province) {
		$this->db->where ( 'province', $province );
		$query = $this->db->get ( 'customers' );
		return $query->result_array ();
	}
	
	function get($id = 0, $limit = 0, $offset = 0) {
		if (! is_numeric ( $id ) || ! is_numeric ( $limit ) || $id < 0 || $limit < 0)
			return null;
		if ($id == 0) {
			if ($limit > 0) {
				$this->db->limit ( $limit, $offset );
			}
			$query = $this->db->get ( 'customers' );
			return $query->result_array ();
		} else {
			$this->db->where ( 'id', $id );
			$query = $this->db->get ( 'customers' );
			if ($query->num_rows () > 0) {
				return $query->first_row ();
			}
		}
	}
	function get_by_fillter($name,$province,$district,$status,$group,$phone,$username){
		$sql = 'SELECT * FROM customers WHERE hidden = 1';
		if($name != ''){
			$sql .= ' AND name LIKE "%'.$name.'%" ';
		}
		if($province != '0'){
			$sql .= ' AND province = "'.$province.'" ';
		}
		if($district != '0'){
			$sql .= ' AND district = "'.$district.'" ';
		}
		if($status != '0'){
			$sql .= ' AND active_status = "'.$status.'" ';
		}
		if($group != '0'){
			$sql .= ' AND customers.group = "'.$group.'" ';
		}
		if($phone != ''){
			$sql .= ' AND phone LIKE "%'.$phone.'%" ';
		}
		if($username != ''){
			$sql .= ' AND username LIKE "%'.$username.'%" ';
		}
		$query = $this->db->query($sql);
		return $query->result_array();
	}

	function get_all_province(){
		$sql = 'SELECT DISTINCT province FROM customers ORDER BY province ASC';
		$query = $this->db->query ($sql);
		return $query->result_array ();
	}
	
	function get_all_district(){
		$sql = 'SELECT DISTINCT district FROM customers ORDER BY district ASC';
		$query = $this->db->query ($sql);
		return $query->result_array ();
	}
}